package com.zlc.common.interceptor;

import com.zlc.common.annotation.RawResponse;
import com.zlc.common.common.entity.BusinessResult;
import com.zlc.common.util.JsonHelper;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.net.URI;

@RestControllerAdvice
public class GlobalControllerAdvice  implements ResponseBodyAdvice<Object> {
    public GlobalControllerAdvice() {
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        RawResponse test = (RawResponse) AnnotationUtils.findAnnotation(returnType.getMethod(), RawResponse.class);
        return test == null;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        URI uri = request.getURI();
        if (uri == null || !uri.toString().contains("/actuator/prometheus") && !uri.toString().contains("/v2/api-docs") && !uri.toString().contains("/v3/api-docs") && !uri.toString().contains("swagger")) {
            if (!(body instanceof BusinessResult) && !(body instanceof ResponseEntity) && !(body instanceof Byte)) {
                return selectedConverterType != null && selectedConverterType.equals(StringHttpMessageConverter.class) ? JsonHelper.toJson(this.getWrapperResponse(request, body)) : this.getWrapperResponse(request, body);
            } else {
                return body;
            }
        } else {
            return body;
        }
    }

    private BusinessResult getWrapperResponse(ServerHttpRequest request, Object e) {
        BusinessResult businessResult = null;
        try{
            businessResult = JsonHelper.coverObject(e, BusinessResult.class);
            businessResult.setData(e);
            businessResult.setStatus("200");
            businessResult.setMessage("OK");
        }catch (Exception ex){}
        if(businessResult == null){
            businessResult = new BusinessResult("OK", "200", e);
        }
        return businessResult;
    }
}
